# Copyright (C) 2009, 2010 Nathan Grubb

from jinja2 import (PackageLoader, Environment, ChoiceLoader,
                    FileSystemLoader)

from toasted.http import HttpResponse
from toasted.settings import (SEND_CONTENT_TYPE_HEADER,
                              TEMPLATE_CONTEXT_PROCESSORS,
                              TEMPLATE_DIRS)    

loader_array = []
for path in TEMPLATE_DIRS:
    loader_array.append(FileSystemLoader(path))
env = Environment(loader=ChoiceLoader(loader_array))

class Template(HttpResponse):
    """An HttpResponse using templates. Using render_to_response to manage
       this class for you is recommended.
    """
    def __init__(self, file, context={}):
        super(Template, self).__init__()
        self.template = env.get_template(file)
        self.context = context
    
        # Process context processors
        for cproc in TEMPLATE_CONTEXT_PROCESSORS:
            context = cproc()
            for key, value in context.items():
                self.context[key] = value

    def render(self):
        """Renders the template. Returns the rendered template."""
        self.content = self.template.render(**self.context)
        return self.content

def render_to_response(file, context={}, headers=[]):
    """A convenience function for getting the correct CGI output for a template,
       including headers.
    """
    t = Template(file, context)
    t.headers = t.headers + headers
    t.render()
    return t.get_response()

def render_template(file, context={}):
    """This function is provided for backwards compatibility, and will be removed
       in Toasted 1.2. It's returns a rendered template. If you're writing new code,
       use render_to_response.
    """
    t = Template(file, context)
    return t.render()